<?php

namespace app\common\model;

use think\facade\Cache;
use think\Model;

/**
 *
 * Class LiveCategoryTopModel
 * @date 2022-05-02
 */
class LiveCategoryTopModel extends Model
{
    protected $connection = 'db_live';

    public function nextCate()
    {
        return $this->hasMany(LiveCategoryModel::class, 'category', 'id');
    }

    protected static function init()
    {
        LiveCategoryModel::afterInsert(function ($user) {
            Cache::store('redis')->rm('live_category_top_list');
        });
        LiveCategoryModel::afterUpdate(function ($user) {
            Cache::store('redis')->rm('live_category_top_list');
        });
        LiveCategoryModel::afterDelete(function ($user) {
            Cache::store('redis')->rm('live_category_top_list');
        });
    }

    public static function lists(): array
    {
        return Cache::store('redis')->remember('live_category_top_list', function () {
            return static::order('sort asc,id desc')->select()->toArray();
        });
    }

    /**
     * 获取顶级分类
     * @param int $status 获取分类状态，0获取所有 1获取有效
     * @return array
     */
    public static function getTopCate($status = 0)
    {
        $list = static::lists();
        $list = array_filter($list, function ($item) use ($status) {
            return !$status || ($item['status'] == $status);
        });
        return array_column($list, 'title', 'id');
    }
}